package smokesignals.data.hibernate;

import com.google.common.base.Preconditions;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import smokesignals.data.QueryHandler;

import java.util.List;

/**
 * @author Henryk Konsek
 */
public class HsqlQueryHandler implements QueryHandler<String> {

    protected SessionFactory sessionFactory;

    public HsqlQueryHandler(SessionFactory sessionFactory) {
        Preconditions.checkNotNull(sessionFactory);
        this.sessionFactory = sessionFactory;
    }

    @Override
    @SuppressWarnings("unchecked") // Hibernate's Query.list() vs Iterable<R>
    public <R> List<R> handle(String query, Object... parameters) {
        Query hibernateQuery = sessionFactory.getCurrentSession().createQuery(query);
        for (int i = 0; i < parameters.length; i++) {
            hibernateQuery.setParameter(i, parameters[i]);
        }
        return hibernateQuery.list();
    }

}
